from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Map
import time,os
# Create your views here.

# 轮播图管理
def mapindex(request):
	ob = Map.objects.all()
	context = {'map':ob}
	return render(request,'myadmin/map/index.html',context)

	
# 会员添加
def mapadd(request):
	
	return render(request,'myadmin/map/add.html')
# 添加处理
def mapinsert(request):
	try:
		ob = Map()
		if request.FILES.get('pic',None):
			ob.pic = upload(request)
		ob.save()
	# return HttpResponse('1')
		return HttpResponse('<script>alert("添加成功");location.href="/admin/mapindex"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/mapadd"</script>')

# # 删除
# def mapdel(request,uid):
	
	
# 	return HttpResponse('1')
# 商品删除
def mapdel(request,uid):
	# return HttpResponse('1')
	ob = Map.objects.get(id=uid)
	os.remove('.'+str(ob.pic))

	ob.delete()
	
	return HttpResponse('<script>alert("删除成功");location.href="/admin/mapindex"</script>')




def upload(request):
	#执行图片的上传
	myfile = request.FILES.get("pic")
	# print(myfile)
	filename = str(time.time())+"."+myfile.name.split('.').pop()

	destination = open("./static/public/map/"+filename,"wb+")
	for chunk in myfile.chunks():      # 分块写入文件  
	    destination.write(chunk)  
	destination.close()
	# 返回上传的文件名
	return '/static/public/map/'+filename



